package com.vitabuybuy.tv.ui.mine

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.view.TimePickerView
import com.blankj.utilcode.util.TimeUtils
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.library.common.toast.XToast
import com.library.common.util.PictureUtils
import com.luck.picture.lib.PictureSelector
import com.library.common.BuildConfig
import com.library.common.ext.setOnclickNoRepeat
import com.library.common.net.NetUrl
import com.tencent.imsdk.TIMCallBack
import com.tencent.imsdk.TIMFriendshipManager
import com.tencent.imsdk.TIMUserProfile
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityPersonainfoBinding
import com.vitabuybuy.tv.dialog.OptionsDialog
import com.vitabuybuy.tv.dto.RegionDto
import com.vitabuybuy.tv.ui.mine.viewmodel.PersonalInfoViewModel
import com.vitabuybuy.tv.widget.selector.BottomDialog
import com.vitabuybuy.tv.widget.selector.SelectedListener
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.activity_personainfo.*
import java.text.SimpleDateFormat
import java.util.*

class PersonalInfoActivity : BaseActivity<PersonalInfoViewModel, ActivityPersonainfoBinding>() {
    companion object {
        fun openActivity(mContext: BaseActivity<*, *>) {
            mContext.startActivity(null, PersonalInfoActivity::class.java)
        }
    }

    private val REQUEST_CODE_CAMMER = 10001
    private val REQUEST_CODE_UPDATE_NICKNAME = 10002
    private var countryId = -1
    private var regionId = -1
    private val picDialog by lazy { OptionsDialog(mContext) }
    private val genderDialog by lazy { OptionsDialog(mContext) }
    private lateinit var timePickerView: TimePickerView
    private var areaDialog: BottomDialog? = null

    override val isUseBaseTitleBar: Boolean
        get() = true
    override val layoutId: Int
        get() = R.layout.activity_personainfo

    override fun initView(savedInstanceState: Bundle?) {
        setTitle(getString(R.string.personal_info))
        mBinding.viewModel = viewModel
    }

    override fun observeData() {
        viewModel.getUserInfo()
        viewModel.userInfoDto.observe(this, androidx.lifecycle.Observer {
            if (it.regionList != null) {
                when (it.regionList.size) {
                    0 -> {
                    }
                    1 -> {
//                        regionId = it.regionList[0].id
                        countryId = it.regionList[0].id
                        tvCountry.text = it.regionList[0].name
//                        tvArea.text = it.regionList[0].name
                    }
                    else -> {
                        countryId = it.regionList[0].id
                        tvCountry.text = it.regionList[0].name
                        var regionStr = ""
                        for ((index, region) in it.regionList.withIndex()) {
                            regionId = region.id
                            if (index != 0) {
                                regionStr += region.name
                            }
                        }
                        tvArea.text = regionStr
                    }
                }
            }
        })
    }

    override fun eventHandling() {
        picDialog.onTwoClick = {
            PictureUtils.openAluamOneRectangle(mContext, REQUEST_CODE_CAMMER)
        }
        picDialog.onOneClick = {
            PictureUtils.openCameraRectangle(mContext, REQUEST_CODE_CAMMER)
        }
        genderDialog.onTwoClick = {
            viewModel.resetUserInfo("gender", getString(R.string.female))
        }
        genderDialog.onOneClick = {
            viewModel.resetUserInfo("gender", getString(R.string.male))
        }
        timePickerView = TimePickerBuilder(this) { date, v -> //选中事件回调
            viewModel.resetUserInfo(
                "birthday",
                TimeUtils.date2String(date, SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()))
            )
        }.setType(booleanArrayOf(true, true, true, false, false, false)) // 默认全部显示
            .setCancelText(getString(R.string.cancel)) // 取消按钮文字
            .setSubmitText(getString(R.string.confirm)) // 确认按钮文字
            .setContentTextSize(16) // 滚轮文字大小
            .setTitleSize(16) // 标题文字大小
            .setTitleText(getString(R.string.choose_time)) // 标题文字
            .setOutSideCancelable(true) // 点击屏幕，点在控件外部范围时，是否取消显示
            .isCyclic(true) // 是否循环滚动
            .setTitleColor(Color.parseColor("#323233")) // 标题文字颜色
            .setTitleBgColor(Color.WHITE) // 标题背景颜色
            .setBgColor(Color.WHITE) // 滚轮背景颜色
            .setDividerColor(Color.parseColor("#DCDDE0"))
            .setOutSideColor(Color.TRANSPARENT)
            .setSubCalSize(14)
            .setSubmitColor(Color.parseColor("#E23225"))
            .setCancelColor(Color.parseColor("#E23225"))
            .setItemVisibleCount(7)
            .build()
        setOnclickNoRepeat(ivAvatar, rlBirthday, rlCountry, rlArea, rlSex, rlName) { v ->
            when (v) {
                ivAvatar -> {
                    AndPermission.with(this)
                        .runtime()
                        .permission(Permission.Group.CAMERA, Permission.Group.STORAGE)
                        .onDenied {
                            if (AndPermission.hasAlwaysDeniedPermission(this, it)) {
                                // 这些权限被用户总是拒绝。
                                XToast.normal(getString(R.string.request_necessary_permissions))
                            }
                        }
                        .onGranted {
                            picDialog.show()
                        }.start()
                }
                rlBirthday -> {
                    timePickerView.apply {
                        setDate(Calendar.getInstance())
                        show(rlBirthday)
                    }
                }
                rlCountry -> {
                    areaDialog = BottomDialog(this, 1)
                    viewModel.getRegionList(null)
                }
                rlArea -> {
                    //这里一定要重新创建
                    if (countryId == -1) {
                        XToast.normal(getString(R.string.pls_choose_country))
                        return@setOnclickNoRepeat
                    }
                    areaDialog = BottomDialog(this, 5)
                    viewModel.getRegionList(countryId)
                }
                rlSex -> {
                    genderDialog.setBtnStr(getString(R.string.male), getString(R.string.female))
                    genderDialog.show()
                }
                rlName -> {
                    UpdateNicknameActivity.openActivity(
                        mContext,
                        viewModel.userInfoDto.value?.nickname,
                        REQUEST_CODE_UPDATE_NICKNAME
                    )
                }
            }
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                REQUEST_CODE_CAMMER -> {
                    val path = PictureSelector.obtainMultipleResult(data)[0].cutPath
                    viewModel.uploadImage(path)
                }
                REQUEST_CODE_UPDATE_NICKNAME -> {
                    viewModel.resetUserInfo("nickname", data?.extras?.getString("nickname"))
                }
            }
        }
    }


    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            1 -> {
                viewModel.resetUserInfo("avatar", NetUrl.FILE_PROFILE + msg.obj as String)
            }
            2 -> {
                when (msg.msg) {
                    "avatar" -> {
                        viewModel.userInfoDto.value?.avatar = msg.obj as String
//                        setSelfProfile(msg.obj as String)
                    }
                    "nickname" -> {
                        viewModel.userInfoDto.value?.nickname = msg.obj as String
                    }
                    "gender" -> {
                        viewModel.userInfoDto.value?.gender = msg.obj as String
                    }
                    "birthday" -> {
                        viewModel.userInfoDto.value?.birthday = msg.obj as String
                    }
                    "address" -> {
                        viewModel.userInfoDto.value?.address = msg.obj as String
                    }
                }
            }
            3 -> {
                areaDialog?.run {
                    this.setDataRegion(msg.obj as MutableList<RegionDto>)
                    this.setOnAddressSelectedListener(object : SelectedListener {
                        override fun onAddressSelected(selectAbles: ArrayList<RegionDto>?) {
                            selectAbles?.run {
//                                if (this.size == 1) {//表明只有国家可选
//                                    regionId = this[0].id
//                                    mBinding.tvArea.text = this[0].name
//                                    mBinding.tvCountry.text = this[0].name
//                                } else {//表明有国家和下属地区
                                    var area = ""
                                    for (selectAble in this) {
                                        area = area + selectAble.name + "  "
                                        regionId = selectAble.id
                                    }
                                    mBinding.tvArea.text = area
                                    areaDialog = null
                                }
                                viewModel.resetUserInfo("regionId", regionId)
//                            }
                        }

                        override fun onClickOnEach(selectAble: RegionDto?) {
                            viewModel.getRegionList(selectAble?.id)
                        }
                    })
                    if (this.isShowing) return
                    this.show()
                }
            }
            4 ->{
                areaDialog?.run {
                    this.setDataRegion(msg.obj as MutableList<RegionDto>)
                    this.setOnAddressSelectedListener(object : SelectedListener {
                        override fun onAddressSelected(selectAbles: ArrayList<RegionDto>?) {
                            selectAbles?.run {
                                if(this[0].id == countryId){
                                    return@run
                                }
                                mBinding.tvCountry.text = this[0].name
                                countryId = this[0].id
                                //地区重新置空
                                regionId = -1
                                mBinding.tvArea.text = ""
                                viewModel.resetUserInfo("regionId", countryId)
                            }
                        }
                        override fun onClickOnEach(selectAble: RegionDto?) {
                        }
                    })
                    if (this.isShowing) return
                    this.show()
                }
            }
        }
    }
//    private fun setSelfProfile(mIconUrl: String) {
//        val hashMap = HashMap<String, Any>()
//        if (!TextUtils.isEmpty(mIconUrl)) {
//            hashMap[TIMUserProfile.TIM_PROFILE_TYPE_KEY_FACEURL] = mIconUrl
//        }
//        TIMFriendshipManager.getInstance().modifySelfProfile(hashMap, object : TIMCallBack {
//            override fun onError(i: Int, s: String) {}
//            override fun onSuccess() {}
//        })
//    }
}
